package com.app.backend.password.check.config;

import com.app.backend.common.utils.JsonUtils;
import com.app.backend.password.check.service.DecryptService;
import com.app.backend.password.check.service.DecryptServiceContext;
import com.app.backend.password.check.vo.DecryptParamBean;
import com.app.backend.password.check.vo.RequestBean;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author zhengjunjie
 */
@Slf4j
@Component
public class RequestInterceptor implements HandlerInterceptor {

    private static final String PASSWORD = "password";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("request请求地址path[{}] uri[{}],thread[{}]", request.getServletPath(), request.getRequestURI(), Thread.currentThread().getId());

        ServletInputStream inputStream = request.getInputStream();
        RequestBean bean = new RequestBean();
        String requestJson = null;
        Map<String, String> requestMap = null;
        String paramJson = Optional.ofNullable(IOUtils.toString(inputStream, "UTF-8")).orElse(null);
        if (!StringUtils.isEmpty(paramJson)) {
            log.info(paramJson);
            if (JsonUtils.isJsonObject(paramJson)) {
                bean = JsonUtils.toObject(paramJson, RequestBean.class);
                requestJson = paramJson;
            } else {
                String[] array = paramJson.split("&");
                requestMap = Arrays.asList(array).stream().map(elem -> elem.split("=")).collect(Collectors.toMap(e -> e[0], e -> e[1]));
            }
        } else {
            // 获取参数
            Map<String, String[]> parameterMap = request.getParameterMap();
            requestMap = new HashMap<>();
            if (parameterMap != null && parameterMap.size() > 0) {
                for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                    String key = entry.getKey();
                    String[] v = entry.getValue();
                    String value = StringUtils.join(v, ",");
                    log.info(key + ":" + value);
                    requestMap.put(key, value);
                    if (PASSWORD.equalsIgnoreCase(key)) {
                        bean.setPassword(value);
                    }
                }
            }
        }
        requestJson = Optional.ofNullable(requestMap).map(u -> JsonUtils.toJson(u)).orElse(requestJson);
        bean.setRequestJson(requestJson);
        RequestBean.set(bean);
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception
            ex)
            throws Exception {
    }
}